package com.hongye.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;
import com.hongye.app.model.OrderTracesModel;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;

/**
 * 快递鸟推送接口 提供给快递鸟
 * @author lifuqiang
 */
public class KdniaoController extends Controller{
	private static Logger log = Logger.getLogger(KdniaoController.class);
	private static final String API_ID = "1267423";
	public KdniaoController() {
		
	}
	
	/**
	 * 快递鸟推送 接口-101-轨迹查询结果, 107-货款状态
	 * @author lifuqiang
	 * 2016-10-21
	 * @throws JSONException 
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked" })
	@Clear
	public void orderTracesPushByJson() {
		String RequestData = this.getPara("RequestData");
		if(log.isInfoEnabled()){log.info("RequestData RequestData="+RequestData);}
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			Object ob = JSONUtil.deserialize(RequestData);
			params = (Map<String, Object>) ob;
		} catch (JSONException e) {
			e.printStackTrace();
		}
//		String EBusinessID = params.get("EBusinessID");
//		String Count = params.get("Count");
		Object PushTime = params.get("PushTime");
		List<Map<String, Object>> Data = (List<Map<String, Object>>) params.get("Data");
		
		//反馈给快递鸟json
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("EBusinessID", API_ID);
		rs.put("UpdateTime", PushTime);
		rs.put("Success", "true");
		rs.put("Reason", "");
		this.renderJson(rs);
		
		//存入数据库
		for(Map<String, Object> map : Data){
			String waybillnumber = (String) map.get("LogisticCode");
			String sql = "select * from order_traces where waybillnumber = '"+waybillnumber+"'";
			OrderTracesModel traces = OrderTracesModel.dao.findFirst(sql);
			try {
				if(traces!=null){
					traces.set("update_time", PushTime).set("data",JSONUtil.serialize(map)).update();
				}else{
					new OrderTracesModel().set("update_time", PushTime).set("data", JSONUtil.serialize(map)).set("waybillnumber", waybillnumber).save();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
}
